//
//  XUIITextInputSelectedRange.m
//  etionUI
//
//  Created by wjxfhxy on 15-4-16.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "XUITextInputSelectedRange.h"

@interface XUIITextInputSelectedRange : NSObject

@end

@implementation XUIITextInputSelectedRange

+ (NSRange)rangeOfSelectedTextInput:(id<UITextInput>)textInput
{
    UITextPosition* beginning = textInput.beginningOfDocument;
    
    UITextRange* selectedRange = textInput.selectedTextRange;
    UITextPosition* selectionStart = selectedRange.start;
    UITextPosition* selectionEnd = selectedRange.end;
    
    NSInteger location = [textInput offsetFromPosition:beginning toPosition:selectionStart];
    NSInteger length = [textInput offsetFromPosition:selectionStart toPosition:selectionEnd];
    
    return NSMakeRange(location, length);
}

+ (void)setTextInput:(id<UITextInput>)textInput selectedRange:(NSRange)range
{
    UITextPosition* beginning = textInput.beginningOfDocument;
    
    UITextPosition* startPosition = [textInput positionFromPosition:beginning offset:range.location];
    UITextPosition* endPosition = [textInput positionFromPosition:beginning offset:range.location + range.length];
    UITextRange* selectionRange = [textInput textRangeFromPosition:startPosition toPosition:endPosition];
    
    [textInput setSelectedTextRange:selectionRange];
}

@end

@implementation UITextField (SelectedRange)

- (NSRange) selectedRange
{
    return [XUIITextInputSelectedRange rangeOfSelectedTextInput:self];
}

- (void) setSelectedRange:(NSRange) range
{
    [XUIITextInputSelectedRange setTextInput:self selectedRange:range];
}

@end

@implementation XUITextView (SelectedRange)

- (NSRange) selectedRange
{
    return [XUIITextInputSelectedRange rangeOfSelectedTextInput:self];
}

- (void) setSelectedRange:(NSRange) range
{
    [XUIITextInputSelectedRange setTextInput:self selectedRange:range];
}

@end